﻿using DevicesView.Entity;
using DevicesView.Model.ViewData;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Devices;
using BCL.BaseLib.Basics;
using BCL.BaseLib;
using System.Windows.Forms;

namespace DevicesView.Logic.Test
{
    public class ResultLogic
    {
        // private static string httpAdd = "http://140.143.203.114:80/api/";
        //private static string httpAdd = "http://localhost:5921/api/";
        private static List<Result> completed;
        private static readonly string httpAdd = App.AppResource.LogicServerAddress;
        public List<TestResult> GetResult(string DoctorCode, DateTime StratTime, DateTime EndTime, Devices.DevicesInformation info = null)
        {
            var dy = new { OrgCode = App.AppResource.CurrentResource.Hospital.Code, DoctorCode, StratTime, EndTime };
            HttpItem hi = new HttpItem { Url = httpAdd + "result/all", Method = HttpMethod.Post, ContentType = "application/json" };
            hi.Content = JsonConvert.SerializeObject(dy).GetBytes(UTF8Encoding.UTF8);
            HttpResult<List<string>> httpResult = WebLogic.GetHttpResult<List<string>>(hi);

            if (!httpResult.Success || httpResult.Result == null || httpResult.Result.Count == 0)
                return null;

            return httpResult.Result.Select<string, TestResult>(o => JsonConvert.DeserializeObject<TestResult>(o)).ToList();

        }


        public List<TestResult> GetResult(Devices.DevicesInformation info = null)
        {
            List<TestResult> results = GetResult(null, DateTime.Parse("2019-1-1"), DateTime.Now, info);
            return results;
        }

        public TestResult GetResultById(int id)
        {
            HttpItem hi = new HttpItem { Url = httpAdd + "result/" + id, Method = HttpMethod.Get };
            HttpResult<string> httpResult = WebLogic.GetHttpResult<string>(hi);
            if (!httpResult.Success || httpResult.Result == null)
                return null;
            return JsonConvert.DeserializeObject<TestResult>(httpResult.Result);
        }

        public List<Doctor> GetOrgDoctors()
        {
            HttpResult<Doctor[]> result = WebLogic.GetHttpResult<Doctor[]>(new HttpItem { Url = httpAdd + "doctors/org/" + App.AppResource.CurrentResource.Hospital.Code, });
            if (!result.Success || result.Result == null || result.Result.Length == 0)
                return null;
            return result.Result.ToList();
        }

        /// <summary>
        /// 查询模板信息
        /// </summary>
        /// <param name="isBackImg">是否显示背景图</param>
        /// <param name="isBackText">是否显示水印文字</param>
        /// <param name="isDeleted">是否已删除</param>
        /// <returns></returns>
        public List<PrintTemp> GetQueryPrintTempAll(int isBackImg = -1, int isBackText = -1, int isDeleted = -1)
        {
            var dy = new { IsBackImg = isBackImg, IsBackText = isBackText, IsDeleted = isDeleted };
            HttpItem hi = new HttpItem { Url = httpAdd + "PrintTemp/QueryAll", Method = HttpMethod.Post, ContentType = "application/json" };
            hi.Content = JsonConvert.SerializeObject(dy).GetBytes(UTF8Encoding.UTF8);
            HttpResult<List<string>> httpResult = WebLogic.GetHttpResult<List<string>>(hi);

            if (!httpResult.Success || httpResult.Result == null || httpResult.Result.Count == 0)
                return null;

            return httpResult.Result.Select<string, PrintTemp>(o => JsonConvert.DeserializeObject<PrintTemp>(o)).ToList();

        }





        public List<Result> Completed
        {
            get
            {
                if (completed == null)
                {
                    completed = Tool.GetObjectByXML<List<Result>>("Completed.xml");
                    if (completed != null)
                        completed.ForEach(o => o.CMD.Result = o);
                }
                return completed;
            }
        }
        public void AddCompleted(Result cmd)
        {
            if (Completed == null)
                completed = new List<Result>();
            completed.Add(cmd);
            SaveCompletedToLocal();
        }
        public void RemoveCompleted(Result cmd)
        {
            if (Completed != null && completed.Remove(cmd))
                SaveCompletedToLocal();
        }
        /// <summary>
        /// 将设备发过来的检查结果先保存到本地
        /// </summary>
        public void SaveCompletedToLocal()
        {
            Tool.ObjectSaveToXML(completed, "Completed.xml");
        }


        public static bool SaveResult(Result result)
        {
            try
            {
                HttpItem hi = new HttpItem { ContentType = "application/json", Url = httpAdd + "result", Method = HttpMethod.Post };
                var newresult = new { result.CMD, result.Date, result.ResultDatas, result.Devices?.Info,result.Remarks };
                string json = JsonConvert.SerializeObject(new
                {
                    OrgCode = App.AppResource.CurrentResource.Hospital.Code,
                    App.AppResource.CurrentResource.AppCode,
                    doctorCode = result.CMD.DoctorId,
                    ResultType = 1,
                    Content = JsonConvert.SerializeObject(newresult)
                });

                hi.Content = UTF8Encoding.UTF8.GetBytes(json);
                HttpResult<string> request = WebLogic.GetHttpResult<string>(hi);
                if (request.Success)
                    return true;
            }
            catch (System.Exception ex)
            {
                BCLApplication.log.Error(ex);
            }
            return false;
        }

        public static HospitalInfo GetHospital(string name)
        {
            HttpItem hi = new HttpItem { Url = httpAdd + "Orgs/" + name, Method = HttpMethod.Get };

            HttpResult<Result114> request = WebLogic.GetHttpResult<Result114>(hi);
            if (request.Success)
                return request.Result?.data;
            return null;
        }
    }

    public class Result114
    {
        public HospitalInfo data { get; set; }
    }
}
